package com.company.Thread;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.StopWatch;

public class CompletableFutureMain {
    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        HashMap<Integer, CompletableFuture<String>> futureMap = new HashMap<>();
        for (int i = 0; i < 4; i++) {
            int finalI = i;
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                try {
                    Thread.sleep(500L);
                } catch (Exception ignored) {
                }
                System.out.println(System.currentTimeMillis() - startTime);
                return Integer.valueOf(finalI).toString();
            });
            futureMap.put(i, future);
            System.out.println(System.currentTimeMillis() - startTime);
        }
        futureMap.forEach((k, v) -> {
            v.join();
        });
        System.out.println(System.currentTimeMillis() - startTime);
        Thread.sleep(5000);
    }

    private void test() {
        System.out.println("cpu的核数:" + Runtime.getRuntime().availableProcessors());
        StopWatch stopWatch = new StopWatch("测试性能");
        stopWatch.start("开始测试");
        Executor executor = Executors.newFixedThreadPool(200);
        List<CompletableFuture<String>> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                String msg = "这是第" + finalI + "个线程在跑" + DateUtil.now();
                try {
                    Thread.sleep(10000 - finalI * 50);
                    // Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return msg;
            }, executor);
            list.add(future);
        }

        list.parallelStream().forEach(item -> {
            System.out.println(item.join() + "|" + DateUtil.now());
        });

        // IntStream.range(0, 100).parallel().forEach(item -> {
        // try {
        // Thread.sleep(1000);
        // System.out.println("完成了：" + item);
        // } catch (InterruptedException e) {
        // e.printStackTrace();
        // }
        // });

        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());
    }
}
